#include "ej_bsp_adc.h"
#include "board_includes.h"
/* private define -------------------------------------------------------- */
#define __ADC_CH_INIT(adc_ch, adc_pin)	\
do { \
	gpio_set_pull_down(adc_pin, 0);  /* 禁用内部下拉电阻 */ \
	gpio_set_pull_up(adc_pin, 0);	  /* 禁用内部上拉电阻 */ \
	gpio_set_die(adc_pin, 0);		  /* 设置为模拟态 */ \
	gpio_set_dieh(adc_pin, 0); 	  /* 设置为模拟态 */ \
	gpio_set_direction(adc_pin, 1);  /* 设置为输入态 */ \
	adc_add_sample_ch(adc_ch);	  /* 配置ADC通道 */ \
} while(0)

/* private function prototypes ---------------------------------------------- */
typedef struct
{
	uint32_t adc_pin;
	uint32_t adc_ch;
}adc_hw_info_t;

/* private variables -------------------------------------------------------- */
static const adc_hw_info_t adc_info_table[] =
{
	{IO_PORTA_00, AD_CH_PA0},
	{IO_PORTA_05, AD_CH_PA5},
	{IO_PORTA_06, AD_CH_PA6},
	{IO_PORTA_08, AD_CH_PA8},
	{IO_PORTC_04, AD_CH_PC4},
	{IO_PORTC_05, AD_CH_PC5},
	{IO_PORTB_01, AD_CH_PB1},
	{IO_PORTB_02, AD_CH_PB2},
	{IO_PORTB_05, AD_CH_PB5},
	{IO_PORTB_09, AD_CH_PB9},
	{IO_PORT_DP , AD_CH_DP },
	{IO_PORT_DM , AD_CH_DM },
	{IO_PORTG_00, AD_CH_PG0},
	{IO_PORTG_01, AD_CH_PG1},
	{IO_PORTG_05, AD_CH_PG5},
	{IO_PORTG_07, AD_CH_PG7},
};


/* private function ---------------------------------------------- */
void ej_bsp_adc_init(void)
{

}

bool ej_bsp_adc_open(uint32_t adc_ch)
{
	for (int i = 0; i < sizeof(adc_info_table)/sizeof(adc_info_table[0]); i++)
	{
		if (adc_info_table[i].adc_ch == adc_ch)
		{
			__ADC_CH_INIT(adc_info_table[i].adc_ch, adc_info_table[i].adc_pin);
			return TRUE;
		}
	}

	if (AD_CH_VBAT == adc_ch)
	{
		return TRUE;
	}

	printf("[Bsp]ADC Init failed: channel not supported !!!!!\n");
	
	return FALSE;
}

bool ej_bsp_adc_close(uint32_t adc_ch)
{
	return FALSE;
}

uint32_t ej_bsp_adc_get_value(uint32_t adc_ch)
{
	uint32_t voltage = 0xFFFF;

	if (AD_CH_VBAT == adc_ch)
	{
		voltage = get_vbat_level()*10;
	}
	else
	{
		voltage = adc_get_voltage(adc_ch);
	}

	return voltage;
}

